import datetime
import json
import time

import numpy as np
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

from stock.models import StockDetail, Stock
from .model_definition import RNN
from utils.stock_data_util import StockDataUtil
import torch


def predict_stock(code):
    if StockDetail.objects.filter(code=code, date=time.strftime("%Y-%m-%d", time.localtime(time.time() - 86400))).count() == 0:
        StockDetail.objects.all().delete()
        print("正在获取股票详细数据")
        stock_data = StockDataUtil.get_stock_data_from_code(code=code, k=20)
        for i in range(len(stock_data)):
            # 日期,开盘,收盘,最高,最低,成交量,成交额,振幅,涨跌幅,涨跌额,换手率
            date = stock_data["日期"][i]
            open = stock_data["开盘"][i]
            close = stock_data["收盘"][i]
            high = stock_data["最高"][i]
            low = stock_data["最低"][i]
            turnover = stock_data["成交量"][i]
            volume = stock_data["成交额"][i]
            amplitude = stock_data["振幅"][i]
            Chg = stock_data["涨跌幅"][i]
            change_amount = stock_data["涨跌额"][i]
            turnover_rate = stock_data["换手率"][i]

            StockDetail.objects.create(code=code, date=date, open=open, close=close, high=high, low=low,
                                       turnover=turnover, volume=volume, amplitude=amplitude, Chg=Chg,
                                       change_amount=change_amount, turnover_rate=turnover_rate)
    else:
        print("数据库已有股票详细数据")
    res = []
    stock_data_df = StockDetail.objects.filter(code=code)
    for stock in stock_data_df:
        res.append({"value": stock.close, "date": stock.date.strftime("%Y-%m-%d")})

    for i in range(5):
        x = res[-10:]  # 从获取前十天的数据
        x = np.array([i["value"] for i in x])
        predict_date = time.localtime(time.time() + 86400 * i)
        res.append({"value": _predict(x), "date": time.strftime("%Y-%m-%d", predict_date)})

    return res[-15:]


def _predict(x):
    rnn = RNN(10)
    rnn.load_state_dict(torch.load('stock/model/srl_model.bin'))
    x_hat = np.mean(x)
    x_std = np.std(x)
    input_data = (x - x_hat) / x_std
    output = rnn(torch.unsqueeze(torch.Tensor(input_data), dim=0))
    output_value = torch.squeeze(output).cpu().detach().numpy()
    prediction = x_hat + output_value
    return prediction


# Create your views here.


@csrf_exempt
def srl(request):
    json_str = request.body
    json_dict = json.loads(json_str)
    code = json_dict.get("code", None)
    if Stock.objects.filter(code=code).exists():
        data = predict_stock(code)
    else:
        data = predict_stock("600519")
    return JsonResponse({'code': 200, 'msg': 'success', 'data': data})


if __name__ == '__main__':
    predict_stock()
